package com.example.userdome.util;

import com.example.userdome.pojo.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Service;

import java.util.Date;

import static io.jsonwebtoken.SignatureAlgorithm.*;
@Service
public class JwtUtils {
    //秘钥
    private static final String secretKey="mySecretKey";
    //生成Jwt
    public String generateToken(User user){
        long currentTime=System.currentTimeMillis();
        return Jwts.builder()
                .setHeaderParam("typ","JWT")
                .setSubject(user.getUsername())
                .setSubject(user.getPassword())
                .setIssuedAt(new Date(currentTime))
                .setExpiration(new Date(currentTime + 3600 * 1000))
                .signWith(ES256,secretKey)
                .compact();
    }
    //解析Jwt
    public  Claims parseToken(String token){
        try{
            return Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            return null;
        }
    }

}
